package com.hzqy.service.industry;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

import javax.annotation.Resource;

import org.apache.commons.codec.digest.DigestUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.hzqy.commons.utils.PublicUtil;
import com.hzqy.commons.utils.SystemConfigUtils;
import com.hzqy.persistence.dao.externalLink.ExternalLinkDao;
import com.hzqy.persistence.dao.industry.IndustryLinkDao;
import com.hzqy.web.vo.WlContentVo;
import com.hzqy.web.vo.industry.IndustryLinkVo;
import com.hzqy.web.vo.industry.ThirdHospitalLinkVo;

@Service
public class IndustryLinkServiceBean {
	protected final Logger LOG = LoggerFactory.getLogger(getClass());
	@Resource
	private ExternalLinkDao externalLinkDao;
	@Resource
	private IndustryLinkDao industryLinkDao;
	public Map<String, Object> postAllJson(IndustryLinkVo industryLinkVo) {
		Locale.setDefault(Locale.ENGLISH);
		Map<String,Object> contentListMap = new HashMap<String, Object>();
		if(industryLinkVo!=null){
			if(industryLinkVo.getLinkId()>0){
				WlContentVo wlContentVo=new WlContentVo();
				wlContentVo.setF_wlc_id(industryLinkVo.getLinkId());
				wlContentVo=externalLinkDao.selectWLContent(wlContentVo);
				if(wlContentVo==null){
					contentListMap.put("msg", "请求异常，请重登后再试");
					contentListMap.put("success", -1);
					return contentListMap;
				}else{
					industryLinkVo.setRequestUrl(wlContentVo.getF_wlc_path());
				}
			}
			Set<String> keyList=industryLinkVo.getData().keySet();
			List<String> removeKey=new ArrayList<String>();
			for (String str : keyList) {
				if(str.indexOf("data_change_type")==-1){
					if(industryLinkVo.getData().get(str+"data_change_type")!=null){
						if("md5".equals(String.valueOf(industryLinkVo.getData().get(str+"data_change_type")).toLowerCase(Locale.ENGLISH))){
							industryLinkVo.getData().put(str, DigestUtils.md5Hex(String.valueOf(industryLinkVo.getData().get(str))));
							removeKey.add(str+"data_change_type");
						}
					}
				}
			}
			for(int i=0;i<removeKey.size();i++){
				industryLinkVo.getData().remove(removeKey.get(i));
			}
			if("post".equals(industryLinkVo.getRequestType().toLowerCase(Locale.ENGLISH))){
				postRequest(industryLinkVo,contentListMap);
			}else{
				get(industryLinkVo, contentListMap);
			}
		}else{
			contentListMap.put("msg", "请求异常，请重登后再试");
			contentListMap.put("success", -1);
		}
		return contentListMap;
	}

	public static void postRequest(IndustryLinkVo industryLinkVo,Map<String, Object> result ) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		String msg = "";
		String success = "0";
		OutputStream os = null;
		InputStream is = null;
		System.out.println(industryLinkVo.getDataString());
		try {// 获取HttpURLConnection连接对象
			URL url = new URL(industryLinkVo.getRequestUrl());
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(2000);
			httpConn.setReadTimeout(3000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			//httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", "UTF-8");
			httpConn.setRequestProperty("Content-Type", industryLinkVo.getContentType());
			httpConn.setRequestMethod("POST");
			os = httpConn.getOutputStream();
			OutputStreamWriter out = new OutputStreamWriter(os, industryLinkVo.getRequestCharset()); // utf-8编码
			out.append(industryLinkVo.getDataString());

			out.flush();
			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				is = httpConn.getInputStream();
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
			close(os);
			close(is);
		}
		System.out.println(msg);
		/*JSONObject jsonObject1 =JSONObject.parseObject(msg);
		if("0".equals(jsonObject1.get("result"))){
			result.put("msg", msg);
			result.put("success", success);
		}else{
			result.put("msg", "");
			result.put("success", success);
		}*/
		result.put("msg", msg);
		result.put("success", success);

	}
	public static void get(IndustryLinkVo industryLinkVo,Map<String, Object> result) {
		PrintWriter writer = null;
		HttpURLConnection httpConn = null;
		String msg = "";
		String success = "0";


		try {// 获取HttpURLConnection连接对象
			URL url = new URL(industryLinkVo.getRequestUrl());
			httpConn = (HttpURLConnection) url.openConnection();
			// 设置连接属性
			httpConn.setConnectTimeout(2000);
			httpConn.setReadTimeout(3000);
			httpConn.setDoInput(true);
			httpConn.setDoOutput(true);
			httpConn.setUseCaches(false);
			httpConn.setRequestProperty("Connection", "Keep-Alive");
			httpConn.setRequestProperty("Charset", industryLinkVo.getRequestType());
			httpConn.setRequestProperty("Content-Type", "text/html");
			httpConn.setRequestMethod("GET");


			int respCode = httpConn.getResponseCode();
			if (respCode == 200) {
				success = "1";
				msg = getStringFromInputStream(httpConn.getInputStream());
			}else{
				success = "2";
				msg = "response_status: " + respCode;
			}
		} catch (Exception e) {
			success = "2";
			//msg = e.getMessage();
		}finally {
			if(httpConn != null)
				httpConn.disconnect();
			close(writer);
		}
		result.put("msg", msg);
		result.put("success", success);
	}
	public static String getStringFromInputStream(InputStream inputStream) {
		StringBuffer str = new StringBuffer();
		BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
		try {
			String temp;
			while ((temp = br.readLine()) != null) {
				str.append(temp);
			}
		} catch (IOException e) {
		} finally {
			close(inputStream);
		}
		return str.toString();
	}
	private static final void close(Closeable closeable) {
		if (closeable != null) {
			try {
				closeable.close();
			} catch (IOException e) {
			}
		}
	}

	public Map<String, Object> thirdHospitalLinkRequest(ThirdHospitalLinkVo thirdHospitalLinkVo) {
		Map<String,Object> contentListMap = new HashMap<String, Object>();
		Map<String,Object> msgListMap = new HashMap<String, Object>();
		IndustryLinkVo industryLinkVo=new IndustryLinkVo();
		JSONObject btn = new JSONObject();
		String callTime=PublicUtil.getCurDateTime("yyyy-MM-dd HH:mm:ss");
		String ddd=PublicUtil.getCurDateTime("yyyyMMddHHmmss");

		List<String> msgList = new ArrayList<String>();
		String authCode= thirdHospitalLinkVo.getTvNo() +"+"+ ddd + "+"+thirdHospitalLinkVo.getInterfaceCode();
		authCode=DigestUtils.md5Hex(authCode);
		btn.put("authCode", authCode);
		btn.put("tvNo", thirdHospitalLinkVo.getTvNo());
		String linkVo=SystemConfigUtils.getSysConfig("link_call_from");
		if(linkVo!=null){
			btn.put("callFrom", linkVo);
		}else{
			btn.put("callFrom", "HZYTYS");
		}
		btn.put("callTime", callTime);
		if(thirdHospitalLinkVo.getInterfaceType()==1){
			btn.put("deptCode", thirdHospitalLinkVo.getDeptCode());
			btn.put("bedNo", thirdHospitalLinkVo.getBedNo());
			industryLinkVo.setData(btn);
			//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/GetPatientInfo");
			industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
			postRequest(industryLinkVo,msgListMap);
			String msg = (String)msgListMap.get("msg");
			msgList.add(msg);
			contentListMap.put("msg", msgList);
			contentListMap.put("success", "1");
		}else if(thirdHospitalLinkVo.getInterfaceType()==2){
			//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/GetMenuList");
			industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
			btn.put("menuKind", thirdHospitalLinkVo.getMenuKind());
			industryLinkVo.setData(btn);
			postRequest(industryLinkVo,contentListMap);
		}else if(thirdHospitalLinkVo.getInterfaceType()==3){
			//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/GetOrderList");
			industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
			industryLinkVo.setData(btn);
			postRequest(industryLinkVo,msgListMap);
			String msg = (String)msgListMap.get("msg");
			if(msg!=null&&msg!=""){
				contentListMap = msgListMap;
			}
		}else if(thirdHospitalLinkVo.getInterfaceType()==4){
			//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/SubmitOrder");
			industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
			btn.put("menuKind", thirdHospitalLinkVo.getMenuKind());
			btn.put("cookbookId", thirdHospitalLinkVo.getCookbookId());
			btn.put("isAlone", thirdHospitalLinkVo.getIsAlone());
			btn.put("mealCode", thirdHospitalLinkVo.getMealCode());
			btn.put("tempOrder", thirdHospitalLinkVo.getTempOrder());
			JSONArray list=new JSONArray();

			if(thirdHospitalLinkVo.getMenuIds()!=null){

				String repastNames = "";
				String menuNames = "";
				String foodNames = "";
				try {
					repastNames = java.net.URLDecoder.decode(thirdHospitalLinkVo.getRepastNames(),"UTF-8");
					menuNames = java.net.URLDecoder.decode(thirdHospitalLinkVo.getMenuNames(),"UTF-8");
					foodNames = java.net.URLDecoder.decode(thirdHospitalLinkVo.getFoodNames(),"UTF-8");
				} catch (UnsupportedEncodingException e) {
					e.printStackTrace();
				}

				if(thirdHospitalLinkVo.getMenuIds().indexOf("-")>=0){

					String[] repastIdArray = thirdHospitalLinkVo.getRepastIds().split("-");
					String[] repastNamesArray = repastNames.split("-");
					String[] menuIdsArray = thirdHospitalLinkVo.getMenuIds().split("-");
					String[] menuCodesArray = thirdHospitalLinkVo.getMenuCodes().split("-");
					String[] menuNamesArray = menuNames.split("-");
					String[] kindOfArray = thirdHospitalLinkVo.getKindOfs().split("-");
					String[] foodIdsArray = thirdHospitalLinkVo.getFoodIds().split("-");
					String[] foodNamesArray = foodNames.split("-");
					String[] dosagesArray = thirdHospitalLinkVo.getDosages().split("-");
					String[] priceArray = thirdHospitalLinkVo.getPrices().split("-");
					String[] isPackageArray = thirdHospitalLinkVo.getIsPackages().split("-");
					String[] isSmallArray = thirdHospitalLinkVo.getIsSmalls().split("-");

					for(int i=0;i<menuIdsArray.length;i++){

						JSONObject order = new JSONObject();
						order.put("repastId", Integer.valueOf(repastIdArray[i]));
						order.put("repastName", repastNamesArray[i]);
						order.put("menuId", menuIdsArray[i]);
						order.put("menuCode", menuCodesArray[i]);
						order.put("menuName", menuNamesArray[i]);
						order.put("kindOf", kindOfArray[i]);
						order.put("foodIds", foodIdsArray[i]);
						order.put("foodNames", foodNamesArray[i]);
						order.put("dosage", dosagesArray[i]);
						order.put("price", Double.valueOf(priceArray[i]));
						order.put("qty", 1);
						order.put("isPackage", Integer.valueOf(isPackageArray[i]));
						order.put("isSmall", Integer.valueOf(isSmallArray[i]));
						list.add(order);

					}

				}else{

					JSONObject order = new JSONObject();
					order.put("repastId", Integer.valueOf(thirdHospitalLinkVo.getRepastIds()));
					order.put("repastName", repastNames);
					order.put("menuId", thirdHospitalLinkVo.getMenuIds());
					order.put("menuName", menuNames);
					order.put("menuCode", thirdHospitalLinkVo.getMenuCodes());
					order.put("kindOf", thirdHospitalLinkVo.getKindOfs());
					order.put("foodIds", thirdHospitalLinkVo.getFoodIds());
					order.put("foodNames", foodNames);
					order.put("dosage", thirdHospitalLinkVo.getDosages());
					order.put("price", Double.valueOf(thirdHospitalLinkVo.getPrices()));
					order.put("qty", 1);
					order.put("isPackage", Integer.valueOf(thirdHospitalLinkVo.getIsPackages()));
					order.put("isSmall", Integer.valueOf(thirdHospitalLinkVo.getIsSmalls()));
					list.add(order);

				}

			}

			btn.put("menuList", list);
			industryLinkVo.setData(btn);
			postRequest(industryLinkVo,contentListMap);
		}else if(thirdHospitalLinkVo.getInterfaceType()==5){
			//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/GetOrderList");
			industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
			btn.put("orderId", thirdHospitalLinkVo.getOrderId());
			industryLinkVo.setData(btn);
			postRequest(industryLinkVo,msgListMap);
			String msg = (String)msgListMap.get("msg");
			if(msg!=null&&msg!=""){
				contentListMap = msgListMap;
			}
		}

		return contentListMap;
	}

	public List<Map<String, String>> selectBedNo(String serverId, String bedNo) {
		Map<String, String> seachMap=new HashMap<String, String>();
		if(serverId!=null){
			seachMap.put("serverId", serverId);
		}
		if(bedNo!=null){
			seachMap.put("bedNo", bedNo);
		}
		List<Map<String, String>> resule=industryLinkDao.selectBedNo(seachMap);
		return resule;
	}

	public List<String> selectPatientInfoByServerId(ThirdHospitalLinkVo thirdHospitalLinkVo) {
		Map<String, String> seachMap=new HashMap<String, String>();
		List<String> patientList=new ArrayList<String>();
		if(thirdHospitalLinkVo.getServerId()!=null){
			seachMap.put("serverId", thirdHospitalLinkVo.getServerId());
			List<Map<String, String>> resule=industryLinkDao.selectBedNo(seachMap);
			if(resule!=null&&resule.size()>0){
				for(int i=0;i<resule.size();i++){
					Map<String,Object> msgListMap = new HashMap<String, Object>();
					thirdHospitalLinkVo.setTvNo(resule.get(i).get("serverId")+resule.get(i).get("bedNo"));
					thirdHospitalLinkVo.setBedNo(resule.get(i).get("bedNo"));
					IndustryLinkVo industryLinkVo=new IndustryLinkVo();
					JSONObject btn = new JSONObject();
					String callTime=PublicUtil.getCurDateTime("yyyy-MM-dd HH:mm:ss");
					String ddd=PublicUtil.getCurDateTime("yyyyMMddHHmmss");

					List<String> msgList = new ArrayList<String>();
					String authCode= thirdHospitalLinkVo.getTvNo() +"+"+ ddd + "+"+thirdHospitalLinkVo.getInterfaceCode();
					authCode=DigestUtils.md5Hex(authCode);
					btn.put("authCode", authCode);
					btn.put("tvNo", thirdHospitalLinkVo.getTvNo());
					String linkVo=SystemConfigUtils.getSysConfig("link_call_from");
					if(linkVo!=null){
						btn.put("callFrom", linkVo);
					}else{
						btn.put("callFrom", "HZYTYS");
					}
					btn.put("callTime", callTime);
					btn.put("deptCode", thirdHospitalLinkVo.getDeptCode());
					btn.put("bedNo", thirdHospitalLinkVo.getBedNo());
					industryLinkVo.setData(btn);
					//industryLinkVo.setRequestUrl("http://wincome.f3322.net:5004/api/TV/GetPatientInfo");
					industryLinkVo.setRequestUrl(thirdHospitalLinkVo.getInterfaceLink());
					postRequest(industryLinkVo,msgListMap);
					String msg = (String)msgListMap.get("msg");
					//msgList.add(msg);
					if(msg!=null){
						patientList.add(msg);
					}
				}
			}
		}
		return patientList;
	}

}
